package com.atlin.project.controller.task;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.task.TaskSpaces;
import com.atlin.project.model.dto.taskSpaces.TaskSpacesAddRequest;
import com.atlin.project.model.dto.taskSpaces.TaskSpacesQueryRequest;
import com.atlin.project.model.dto.taskSpaces.TaskSpacesUpdateRequest;
import com.atlin.project.model.enums.task.TaskSpaceTypeEnum;
import com.atlin.project.model.vo.TaskSpacesVO;
import com.atlin.project.model.vo.task.UserTaskCommonVO;
import com.atlin.project.service.SysUserService;
import com.atlin.project.service.task.TaskSpacesService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 模版接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/taskSpaces")
public class TaskSpacesController {

    @Resource
    private TaskSpacesService taskSpacesService;

    @Resource
    private SysUserService sysUserService;

    // region 增删改查

    /**
     * 创建
     *
     * @param taskSpacesAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTaskSpaces(@RequestBody TaskSpacesAddRequest taskSpacesAddRequest, HttpServletRequest request) {
        if (taskSpacesAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TaskSpaces taskSpaces = new TaskSpaces();
        BeanUtils.copyProperties(taskSpacesAddRequest, taskSpaces);

        taskSpacesService.valid(taskSpaces, true);
        SysUser loginUser = sysUserService.getLoginUser(request);

        taskSpaces.setCreatorId(loginUser.getId());

        boolean result = taskSpacesService.save(taskSpaces);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newTaskSpacesId = taskSpaces.getId();
        return ResultUtils.success(newTaskSpacesId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTaskSpaces(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        TaskSpaces oldtaskSpaces = taskSpacesService.getById(id);
        ThrowUtils.throwIf(oldtaskSpaces == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldtaskSpaces.getCreatorId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = taskSpacesService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param taskSpacesUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTaskSpaces(@RequestBody TaskSpacesUpdateRequest taskSpacesUpdateRequest) {
        if (taskSpacesUpdateRequest == null || taskSpacesUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TaskSpaces taskSpaces = new TaskSpaces();
        BeanUtils.copyProperties(taskSpacesUpdateRequest, taskSpaces);

        // 参数校验
        taskSpacesService.valid(taskSpaces, false);
        long id = taskSpacesUpdateRequest.getId();
        // 判断是否存在
        TaskSpaces oldtaskSpaces = taskSpacesService.getById(id);
        ThrowUtils.throwIf(oldtaskSpaces == null, ErrorCode.NULL_ERROR);

        boolean result = taskSpacesService.updateById(taskSpaces);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<TaskSpaces> getTaskSpacesById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TaskSpaces taskSpaces = taskSpacesService.getById(id);
        if (taskSpaces == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!taskSpaces.getCreatorId().equals(loginUser.getId()) && !sysUserService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(taskSpaces);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TaskSpacesVO> getTaskSpacesVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TaskSpaces taskSpaces = taskSpacesService.getById(id);
        if (taskSpaces == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        TaskSpacesVO taskSpacesVO = TaskSpacesVO.objToVo(taskSpaces);
        return ResultUtils.success(taskSpacesVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param taskSpacesQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TaskSpacesVO>> listTaskSpacesVOByPage(@RequestBody TaskSpacesQueryRequest taskSpacesQueryRequest,
                                                                   HttpServletRequest request) {
        long current = taskSpacesQueryRequest.getCurrent();
        long size = taskSpacesQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<TaskSpaces> taskSpacesPage = taskSpacesService.page(new Page<>(current, size),
                taskSpacesService.getQueryWrapper(taskSpacesQueryRequest));

        Page<TaskSpacesVO> taskSpacesVOPage = taskSpacesService.getTaskSpacesVOPage(taskSpacesPage, request);

        return ResultUtils.success(taskSpacesVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param taskSpacesQueryRequest 查询参数
     * @param request                查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<TaskSpaces>> listTaskSpacesByPage(@RequestBody TaskSpacesQueryRequest taskSpacesQueryRequest,
                                                               HttpServletRequest request) {
        long current = taskSpacesQueryRequest.getCurrent();
        long size = taskSpacesQueryRequest.getPageSize();
        Page<TaskSpaces> taskSpacesPage = taskSpacesService.page(new Page<>(current, size),
                taskSpacesService.getQueryWrapper(taskSpacesQueryRequest));
        return ResultUtils.success(taskSpacesPage);
    }

    // endregion

    /**
     * 获取我的空间列表
     *
     * @param request
     * @return 空间列表
     */
    @PostMapping("/list/listMyTaskSpaces")
    public BaseResponse<List<TaskSpaces>> listMyTaskSpaces(HttpServletRequest request) {
        SysUser loginUser = sysUserService.getLoginUser(request);
        LambdaQueryWrapper<TaskSpaces> wrapper = new QueryWrapper<TaskSpaces>().lambda()
                .eq(TaskSpaces::getCreatorId, loginUser.getId());
        return ResultUtils.success(taskSpacesService.list(wrapper));
    }

    // region 基础信息

    /**
     * 获取任务空间类型枚举列表
     *
     * @return 任务空间类型枚举
     */
    @GetMapping("/getTaskSpaceTypeList")
    public BaseResponse<List<UserTaskCommonVO>> getTaskSpaceTypeList() {

        ArrayList<UserTaskCommonVO> res = new ArrayList<>();
        for (TaskSpaceTypeEnum taskSpaceTypeEnum : TaskSpaceTypeEnum.values()) {
            UserTaskCommonVO userTaskCommonVO = new UserTaskCommonVO();
            BeanUtils.copyProperties(taskSpaceTypeEnum, userTaskCommonVO);
            res.add(userTaskCommonVO);
        }

        return ResultUtils.success(res);
    }

    // endregion


}
